/*
 * @Author: 韩旭
 * @Date: 2021-08-24 16:49:28
 * @LastEditTime: 2021-08-27 14:51:06
 * @LastEditors: 韩旭
 * @Description:
 *      <div v-copy> 单击复制 </div>
        <div v-copy.dblclick> 双击复制 </div>
        <div v-copy.icon> icon复制 </div>
 * @FilePath: \tvmscanner-front\plugins\directive\copy.js
 */
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const handleClick = (text) => {
      if (!document.getElementById('copyTarget')) {
        const copyTarget = document.createElement('input');
        copyTarget.setAttribute(
          'style',
          'position:fixed;top:0;left:0;opacity:0;z-index:-1000;',
        );
        copyTarget.setAttribute('id', 'copyTarget');
        document.body.appendChild(copyTarget);
      }

      const input: any = document.getElementById('copyTarget');
      input.value = text;
      input.select();
      document.execCommand('copy');
    };

    const addCopyListener = (el, binding) => {
      const handleClickWrapper = () => handleClick(el.innerText);

      const handleIconClick = () => {
        if (el.hasIcon) return;
        const iconElement = document.createElement('i');
        iconElement.setAttribute('class', 'el-icon-document-copy');
        iconElement.setAttribute('style', 'margin-left:5px');
        el.appendChild(iconElement);
        el.hasIcon = true;
        iconElement.addEventListener('click', handleClickWrapper);
        iconElement.style.cursor = 'copy';
      };

      const newClass = el.className.split(' ');
      newClass.push('copy');

      el.className = newClass.join(' ');

      if (binding.modifiers.dblclick) {
        el.ondblclick = handleClickWrapper;
        el.style.cursor = 'copy';
      } else if (binding.modifiers.icon) {
        el.hasIcon = false;
        handleIconClick();
      } else {
        el.onclick = handleClickWrapper;
        el.style.cursor = 'copy';
      }
    };

    onMounted(() => {
      const el = ref(null);
      const binding = ref(null);
      addCopyListener(el.value, binding.value);
    });

    return {};
  },
};
